package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.common.CommonDishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("adminDishService")
@Slf4j
public class DishServiceImpl implements com.sky.service.admin.DishService {

    private final DishMapper dishMapper;
    private final DishFlavorMapper dishFlavorMapper;
    private final SetmealDishMapper setmealDishMapper;
    private final SetmealMapper setmealMapper;
    private final CommonDishService commonDishService;

    @Autowired
    public DishServiceImpl(DishMapper dishMapper, DishFlavorMapper dishFlavorMapper, SetmealDishMapper setmealDishMapper, SetmealMapper setmealMapper, CommonDishService commonDishService) {
        this.dishMapper = dishMapper;
        this.dishFlavorMapper = dishFlavorMapper;
        this.setmealDishMapper = setmealDishMapper;
        this.setmealMapper = setmealMapper;
        this.commonDishService = commonDishService;
    }

    /**
     * 新增菜品以及口味
     *
     * @param dishDTO 菜品DTO
     */
    @Override
    @Transactional
    public void saveDishWitchFlavor(DishDTO dishDTO) {
        log.info("执行 新增菜品以及口味 业务: {}",dishDTO);
        Dish dish = new Dish();
        //向菜品表插入一条数据
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insertDish(dish);

        //获取插入后所得到的菜品id
        Long id = dish.getId();

        //向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {//如果集合非空，集合哪有元素

            //便利集合， 使每个口味上赋上菜品id
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(id));

            dishFlavorMapper.insertFlavor(flavors);
        }
    }

    /**
     * 批量删除菜品
     * @param dishIds 菜品id集合
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> dishIds){
        log.info("执行 批量删除菜品 业务: {}",dishIds);
        //判断菜品能否删除
        //菜品是否正在售卖
        for (Long id : dishIds) {
            Dish dish = dishMapper.getDishById(id);
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                //当前菜品售卖中
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //是否被套餐关联了
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
        if (setmealIds != null && !setmealIds.isEmpty()) {
            //商品被关联了
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        for (Long id : dishIds) {
            //删除菜品表中的菜品数据
            dishMapper.deleteById(id);
            //删除关联口味
            dishFlavorMapper.deleteFlavorByDishId(id);
        }
    }

    /**
     * 根据菜品DTO修改菜品以及口味
     *
     * @param dishDTO 菜品DTO
     */
    @Override
    @Transactional
    public void updateDishWithFlavor(DishDTO dishDTO) {
        log.info("执行 修改菜品以及口味 业务: {}",dishDTO);
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改菜品id
        dishMapper.updateDish(dish);
        //先全部删除菜品口味
        dishFlavorMapper.deleteFlavorByDishId(dishDTO.getId());
        //再插入新的菜品口味
        //向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {//如果集合非空，集合哪有元素

            //便利集合， 使每个口味上赋上菜品id
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDTO.getId()));

            dishFlavorMapper.insertFlavor(flavors);
        }
    }

    /**
     * 菜品启售停售
     *
     * @param status 菜品状态
     * @param dishId 菜品id
     */
    @Override
    public void startOrStopDish(Integer status, Long dishId) {
        log.info("执行 菜品启售停售 业务: {}", dishId);
        Dish dish = Dish.builder()
                .id(dishId)
                .status(status)
                .build();
        dishMapper.updateDish(dish);
        if (Objects.equals(status, StatusConstant.DISABLE)) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(dishId);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && !setmealIds.isEmpty()) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.updateSetmeal(setmeal);
                }
            }
        }
    }

    /**
     * 分页查询菜品
     *
     * @param dishPageQueryDTO 菜品分页实体类DTO
     * @return 分页数据包
     */
    @Override
    public PageResult pageQueryDish(DishPageQueryDTO dishPageQueryDTO) {
        log.info("执行 分页查询菜品 业务: {}",dishPageQueryDTO);
            PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
            long total;
            List<DishVO> records;

            try (Page<DishVO> page = dishMapper.pageQueryDish(dishPageQueryDTO)) {
                total = page.getTotal();
                records = page.getResult();
            }

            return new PageResult(total, records);
    }

    /**
     * 根据菜品id查询菜品
     *
     * @param dishId 菜品Id
     * @return 菜品实体类VO
     */
    @Override
    public DishVO getByDishIdWithFlavor(Long dishId) {
        //根据菜品id查询菜品数据
        Dish dish = dishMapper.getDishById(dishId);
        //根据菜品id查询口味
        List<DishFlavor> dishFlavor = dishFlavorMapper.getFlavorByDishId(dishId);
        DishVO dishVO = new DishVO();
        //DishVO中的categoryName（菜品关联口味）不是必要的，所以不需要拷贝
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavor);
        return dishVO;
    }

    /**
     * 根据分类id查询菜品
     * 重复代码
     * @param dish 菜品实体类
     * @return 菜品实体类VO
     */
    @Override
    public List<DishVO> listDishWithFlavor(Dish dish) {
        return commonDishService.listDishWithFlavor(dish);
    }
}
